# -*- coding:UTF-8 -*-#

'''
@author: qianwp
'''

from popcan.core.structures import Singleton
from popcan.globals.settings import ServerSettings
from popcan.db.daos import UIDDaos
from popcan.helper.loggerhelper import QueueLogger,Module

class UIDPrefix:
    Cust = 0
    Album = 1
    Compst = 2
    Photo = 3
    Comment = 4

class UIDLoader(Singleton):
    
    def loadUIDs(self):
        QueueLogger().info(Module.Load, 'loading model uids')
        cur = UIDDaos().getCurCustId(CustUIDCreator().minuid(), CustUIDCreator().maxuid())
        CustUIDCreator().initcur(cur)
        cur = UIDDaos().getCurAlbumId(AlbumUIDCreator().minuid(), AlbumUIDCreator().maxuid())
        AlbumUIDCreator().initcur(cur)
        cur = UIDDaos().getCurCompstId(CompositUIDCreator().minuid(), CompositUIDCreator().maxuid())
        CompositUIDCreator().initcur(cur)
        cur = UIDDaos().getCurPhotoId(PhotoUIDCreator().minuid(), PhotoUIDCreator().maxuid())
        PhotoUIDCreator().initcur(cur)
        cur = UIDDaos().getCurCommentId(CommentUIDCreator().minuid(), CommentUIDCreator().maxuid())
        CommentUIDCreator().initcur(cur)
        QueueLogger().info(Module.Load, 'model uids loaded success')

class UIDCreator(Singleton):
    
    def initcur(self,cur):
        self.cur = cur if cur else self.minuid()

    def minuid(self):
        return (ServerSettings.serverId << 56) | (self.prefix() << 48)

    def maxuid(self):
        return (ServerSettings.serverId << 56) | (((self.prefix() + 1) << 48) - 1)

    def prefix(self):
        raise NotImplementedError('UID should have a prefix')

    def nextuid(self):
        self.cur = self.cur + 1
        return self.cur

class CustUIDCreator(UIDCreator):
    
    def prefix(self):
        return UIDPrefix.Cust
    
class AlbumUIDCreator(UIDCreator):
    
    def prefix(self):
        return UIDPrefix.Album

class CompositUIDCreator(UIDCreator):
    
    def prefix(self):
        return UIDPrefix.Compst
  
class PhotoUIDCreator(UIDCreator):
    
    def prefix(self):
        return UIDPrefix.Photo

class CommentUIDCreator(UIDCreator):
    
    def prefix(self):
        return UIDPrefix.Comment